<template>
  <div>
    <div style="display: flex;margin-top: 10px;">
      <div>
        <el-button @click="print" :loading="printShow" type="primary">开始打印{{defaultData.length}}条</el-button>
        <el-input v-model="pdfNum" style="width: 200px;"></el-input>
      </div>
      <div style="margin-left: 20px;" v-show="!this.sessionDocDataIds">
        <el-radio v-model="radio" label="1" :disabled="printShow" border>周计划{{weekCount}}条</el-radio>
        <el-radio v-model="radio" label="2" :disabled="printShow" border>其他计划{{otherCount}}条</el-radio>
        <span>（周计划里面包含课时计划）</span>
      </div>
    </div>
    <div v-if="printShow" id="playerDetailPrint" style="width: 800px;padding:50px 50px 50px 50px;overflow: visible;">
      <weekAndClassPlanPrintAuto v-if="currentDocClassId==33||currentDocClassId==34" id="myPrint" :previewData="printData"
        :docClassId="currentDocClassId" />
      <otherPlanPrint v-else id="myPrint" :previewData="printData" :docClassId="currentDocClassId" />
    </div>
  </div>
</template>

<script>
  import html2Canvas from 'html2canvas'
  import JsPDF from 'jspdf'
  // import VueHtml2pdf from 'vue-html2pdf'
  import {
    plan_doc_all,
    allType,
    plan_doc_select,
    batchPrint
  } from '@/api/plan.js'
  import {
    sport_by_org,
    currentRoleEmployee,
    plan_doc_available
  } from '@/api/dict.js'
  import otherPlanPrint from "@/components/print/otherPlanPrint.vue"
  import weekAndClassPlanPrintAuto from "@/components/utils/weekAndClassPlanPrintAuto.vue"
  import htmlDocx from 'html-docx-js/dist/html-docx';
  import saveAs from 'file-saver';
  export default {
    components: {
      otherPlanPrint,
      weekAndClassPlanPrintAuto,
    },
    data() {
      return {
        printData: {},
        defaultData: [],
        fileName: '',
        download: false,
        pdfSave: 1,
        pdfNum: 0,
        currentDocClassId: 0,
        dict_sport: {},
        dict_emp: {},
        nameArr: [],
        dict_docClass: {},
        loading: false,
        printShow: false,
        radio: '1',
        weekCount: null,
        otherCount: null,
        weekArr: [],
        otherArr: [],
        recursionFlage: true,
        page: '',
        sessionDocDataIds: [],
      }
    },
    computed: {
      pdfOptions() {
        return {
          margin: [0, 5, 0, 5],
          pagebreak: {
            mode: 'avoid-all'
          }
        }
      },
    },
    created() {
      this.pdfNum = window.localStorage.getItem('pdfNum')
      this.radio = window.localStorage.getItem('radio')
      if(!this.pdfNum) this.pdfNum = 0
      if(!this.radio) this.radio = 1
      this.init_dict().then(()=>{
        this.printShow = false
      })
    },
    watch: {
      radio(val){
        window.localStorage.setItem('radio',val)
        if(this.radio == '1'){
          this.defaultData = this.weekArr
        }else{
          this.defaultData = this.otherArr
        }
      }
    },
    methods: {
      init_dict() {
        this.printShow = true
        return new Promise((resolve, reject) => {
          plan_doc_available().then(res=>{
            this.dict_docClass = res
          }).then(()=>{
            sport_by_org().then(res => {
              this.dict_sport = res
            }).then(() => {
              currentRoleEmployee().then(res => {
                this.dict_emp = res
              }).then(()=>{
                this.weekCount = 0
                this.otherCount = 0
                let allArr = []
                for(let key in this.dict_docClass){
                  if(key != 34){
                    plan_doc_select({data:{docClassId:key}}).then(res => {
                      if (res.code === 200 && res.data.length != 0) {
                        allArr.push(...res.data)
                      }
                    }).then(()=>{
                      this.weekArr = []
                      this.otherArr = []
                      allArr.forEach(item=>{
                        if(item.docClassId == 33) {
                          this.weekArr.push(item)
                          this.weekCount = this.weekArr.length
                        }else{
                          this.otherArr.push(item)
                          this.otherCount = this.otherArr.length
                        }
                      })
                      if(this.radio == '1'){
                        this.defaultData = this.weekArr
                      }else{
                        this.defaultData = this.otherArr
                      }
                      this.sessionDocDataIds = JSON.parse(window.localStorage.getItem('sessionDocDataIds'))
                      if(this.sessionDocDataIds&&this.sessionDocDataIds.length!=0){
                        let arr = []
                        this.sessionDocDataIds.forEach(item=>{
                          if(item.docClassId!=34){
                            arr.push(item)
                          }
                        })
                        this.defaultData = arr
                      }
                      resolve()
                    })
                  }
                }
              })
            })
          })
        })
      },
      print() {
        this.length = this.defaultData.length.toString().length;
        this.max = Math.pow(10,this.length)
        window.localStorage.setItem('pdfNum',this.pdfNum)
        if (this.defaultData.length == 0) {
          this.$message.error('没有数据怎么打印？！！！')
          return
        }
        if (this.pdfNum != this.defaultData.length) {
          // if(this.radio == '1'){
          //   this.weekPlanPrint(this.defaultData[this.pdfNum])
          // }else{
          //   this.otherPlanPrint(this.defaultData[this.pdfNum])
          // }
          this.weekPlanPrint(this.defaultData[this.pdfNum])
        }
      },
      // otherPlanPrint(item) {
      //   let data = {
      //     docDataId: item.docDataId,
      //     docClassId: item.docClassId,
      //   }
      //   this.currentDocClassId = item.docClassId
      //   allType(data).then(res => {
      //     if (res.code === 200) {
      //       this.printData = res.data
      //       this.printShow = true
      //     }
      //   }).then(() => {
      //     let dom = document.getElementById('playerDetailPrint')
      //     let count = ''
      //     let planName = (this.dict_sport[item.sportId] || 'XXX') + '-' + (this.dict_emp[item.empId] || 'XXX') +
      //       '-' + item.name
      //     this.nameArr.push(planName)
      //     let num = 0
      //     this.nameArr.forEach(item => {
      //       if (item == planName) {
      //         num++
      //       }
      //     })
      //     count = (num).toString()
      //     if (count.length == 1) {
      //       count = '-00' + count
      //     } else if (count.length == 2) {
      //       count = '-0' + count
      //     } else {
      //       count = '-' + count
      //     }
      //     this.getPdfFromHtml(dom, planName + count)
      //   })
      // },
      weekPlanPrint(item) {
        let data = {
          docDataId: item.docDataId,
          docClassId: item.docClassId,
        }
        this.currentDocClassId = item.docClassId
        allType(data).then(res => {
          if (res.code === 200) {
            this.printData = res.data
            this.printShow = true
          }
        }).then(() => {
          // let dom = document.getElementById('playerDetailPrint')
          // let dom = document.querySelectorAll('#playerDetailPrint .week')
          let count = ''
          let planName = (this.dict_sport[item.sportId] || '运动项目信息异常') + '-' + (this.dict_emp[item.empId] || '教练员信息异常') +
            '-' + item.name
          this.nameArr.push(planName)
          // 这里num改成请求回来的所有条目的计数 比如返回数据有10000条，所有训练计划从00001开始到10000 这样编号 不分运动员
          let num = this.pdfNum
          // for循环亟待改进
          // this.nameArr.forEach(item => {
          //   if (item == planName) {
          //     num++
          //   }
          // })

            let currentCount = this.max+num;
            currentCount = currentCount.toString()
            count = currentCount.substring(1,this.length+1)


          // 这种形式写最多支持999
          // count = (num).toString()
          // if (count.length == 1) {
          //   count = '-0000' + count
          // } else if (count.length == 2) {
          //   count = '-000' + count
          // } else if(count.length == 3){
          //   count = '-00' + count
          // }else if(count.length == 4){
          //   count = '-0' + count
          // }else {
          //   count = '-' + count
          // }
          this.pdfFileName =  planName + count
          const divEl = document.getElementById('playerDetailPrint')
          this.page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${divEl.innerHTML}</body></html>`
          const converted = htmlDocx.asBlob(this.page);
          // 用 FielSaver.js里的保存方法 进行输出
          saveAs(converted, this.pdfFileName+'.docx')
          // this.genPdf(dom,this.pdfFileName);
          // this.pdf = new JsPDF('x', 'pt', 'a4');
          // this.pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');
          // this.genPdf(this.pdf,dom,0,0);
          let timer = setTimeout(()=>{
            this.printShow = false
            this.pdfNum = parseInt(this.pdfNum)
            this.pdfNum += 1
            this.print()
            clearTimeout(timer)
          },200)
        })
      },
      genPdf(dom,pdfFileName){
      // genPdf(pdf,dom,domIndex,pageIndex){
        // if(!this.recursionFlage){
        //    this.pdfSave =pdf.save(this.pdfFileName + '.pdf')
        //    // this.printShow = false
        //    // this.pdfNum = parseInt(this.pdfNum)
        //    // this.pdfNum += 1
        //    // this.print()
        //   return;
        // }
        // pdf.addPage();
        // pdf.setPage(pageIndex+1);
        // new Promise(resolve=>{
        //            // dom.forEach((ele,eleindex)=>{
        //              // this.getPdfFromHtml(item,index)
        //              let ele = dom[domIndex];
        //              html2Canvas(ele, {
        //                dpi: window.devicePixelRatio * 4,
        //                scale: 4,
        //                useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
        //                allowTaint: false,
        //                height: ele.offsetHeight,
        //                width: ele.offsetWidth,
        //                windowWidth: document.body.scrollWidth,
        //                windowHeight: document.body.scrollHeight,
        //              }).then(canvas => {
        //                this.dialogVisible = true;
        //                const _this = this;
        //                //未生成pdf的html页面高度
        //                var leftHeight = canvas.height;
        //                var a4Width = 595.28 - 40
        //                var a4Height = 841.89
        //                //一页pdf显示html页面生成的canvas高度;
        //                var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);

        //                //pdf页面偏移
        //                var position = 0;

        //                let pageData = canvas.toDataURL('image/jpeg', 1.0);

        //                var index = 1,
        //                  canvas1 = document.createElement('canvas'),
        //                  height;

        //                // $('.head-content').append($(
        //                //   '<div class="pdfTip">' +
        //                //   '   <div>正在生成第<span class="pdfProgress">1</span>页，共<span class="pdfTotal"></span>页...' +
        //                //   '</div>'));
        //                // pageIndex++;
        //                pageIndex = createImpl(canvas,pageIndex)
        //                console.log(pageIndex)
        //                function createImpl(canvas,innerPageIndex) {
        //                  if (leftHeight > 0) {
        //                    index++;
        //                    var checkCount = 0;
        //                    if (leftHeight > a4HeightRef) {
        //                      var i = position + a4HeightRef;
        //                      for (i = position + a4HeightRef; i >= position; i--) {
        //                        var isWrite = true
        //                        for (var j = 0; j < canvas.width; j++) {
        //                          var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

        //                          if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
        //                            isWrite = false
        //                            break
        //                          }
        //                        }
        //                        if (isWrite) {
        //                          checkCount++
        //                          if (checkCount >= 10) {
        //                            break
        //                          }
        //                        } else {
        //                          checkCount = 0
        //                        }
        //                      }
        //                      height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
        //                      if (height <= 0) {
        //                        height = a4HeightRef;
        //                      }
        //                    } else {
        //                      height = leftHeight;
        //                    }

        //                    canvas1.width = canvas.width;
        //                    canvas1.height = height;

        //                    // console.log(index, 'height:', height, 'pos', position);

        //                    var ctx = canvas1.getContext('2d');
        //                    ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);

        //                    var pageHeight = Math.round(a4Width / canvas.width * height);
        //                    // pdf.setPageSize(null, pageHeight)
        //                    // if (position != 0) {
        //                      pdf.addPage();
        //                      pdf.setPage(innerPageIndex+1);
        //                      innerPageIndex++
        //                    // }
        //                    pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 20, 20, a4Width, a4Width / canvas1.width *
        //                      height);
        //                    leftHeight -= height;
        //                    position += height;
        //                    // this.pdf.output();
        //                    console.log("第"+innerPageIndex+"页")
        //                    if (leftHeight > 0) {
        //                      console.log('if',innerPageIndex)
        //                      return createImpl(canvas,innerPageIndex)

        //                      // setTimeout(createImpl, 500, canvas);
        //                    } else {
        //                      console.log('else',innerPageIndex)
        //                      if(domIndex == 7) {
        //                        _this.recursionFlage = false
        //                      }
        //                      return innerPageIndex
        //                        // this.pdfSave = this.pdf.save(this.pdfFileName + '.pdf');
        //                    }
        //                  }
        //                }
        //                //当内容未超过pdf一页显示的范围，无需分页
        //                // if (leftHeight < a4HeightRef) {
        //                  // this.pdf.addImage(pageData, 'JPEG', 20, 20, a4Width, a4Width / canvas.width * leftHeight);
        //                   // console.log("第一页的第二次添加")
        //                  this.dialogVisible = true;
        //                  // this.pdf.output();
        //                  // this.iframeSrc = pdf.output('dataurlstring');
        //                  // debugger;
        //                    // this.pdfSave = this.pdf.save(this.pdfFileName + '.pdf')
        //                // } else {
        //                  // try {
        //                    // this.pdf.deletePage(0);
        //                  //   // $('.pdfTip').show();
        //                  //   // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
        //                    // setTimeout(createImpl, 500, canvas);
        //                  // } catch (err) {
        //                  //   console.log(err);
        //                  // }
        //                // }
        //                // console.log(eleindex)
        //                // if(eleindex==7){
        //                  domIndex++;
        //                  resolve([pdf,dom,domIndex,pageIndex])

        //                // }
        //              })
        //            // }
        //            // )
        // }).then(([pdf,dom,domIndex,pageIndex])=>{
        //   // console.log("pdf"+pdf)
        //   // console.log("dom"+dom)
        //   // console.log("domIndex"+domIndex)
        //   this.genPdf(pdf,dom,domIndex,pageIndex);

        // })

            const scale = 2

            // 滚动到顶部，避免打印不全
            document.documentElement.scrollTop = 0

            html2Canvas(dom, {
                allowTaint: true, // Whether to allow cross-origin images to taint the canvas
                scale // The scale to use for rendering. Defaults to the browsers device pixel ratio.
            }).then((canvas) => {
                const contentWidth = canvas.width / scale
                const contentHeight = canvas.height / scale
                const pdf = new JsPDF('', 'pt', [contentWidth, contentHeight])
                const pageData = canvas.toDataURL('image/jpeg', 1.0)

                pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight)
                pdf.save(`${pdfFileName}.pdf`)
            })

      },
      getPdfFromHtml(ele, pdfFileName) {
        html2Canvas(ele, {
          dpi: window.devicePixelRatio * 4,
          scale: 4,
          useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
          allowTaint: false,
          height: ele.offsetHeight,
          width: ele.offsetWidth,
          windowWidth: document.body.scrollWidth,
          windowHeight: document.body.scrollHeight,
        }).then(canvas => {
          this.dialogVisible = true;
          const _this = this;
          //未生成pdf的html页面高度
          var leftHeight = canvas.height;
          var a4Width = 595.28
          var a4Height = 841.89
          //一页pdf显示html页面生成的canvas高度;
          var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);

          //pdf页面偏移
          var position = 0;

          var pageData = canvas.toDataURL('image/jpeg', 1.0);

          var pdf = new JsPDF('x', 'pt', 'a4');
          var index = 1,
            canvas1 = document.createElement('canvas'),
            height;
          pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');

          // $('.head-content').append($(
          //   '<div class="pdfTip">' +
          //   '   <div>正在生成第<span class="pdfProgress">1</span>页，共<span class="pdfTotal"></span>页...' +
          //   '</div>'));
          function createImpl(canvas) {
            if (leftHeight > 0) {
              index++;
              var checkCount = 0;
              if (leftHeight > a4HeightRef) {
                var i = position + a4HeightRef;
                for (i = position + a4HeightRef; i >= position; i--) {
                  var isWrite = true
                  for (var j = 0; j < canvas.width; j++) {
                    var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

                    if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                      isWrite = false
                      break
                    }
                  }
                  if (isWrite) {
                    checkCount++
                    if (checkCount >= 10) {
                      break
                    }
                  } else {
                    checkCount = 0
                  }
                }
                height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
                if (height <= 0) {
                  height = a4HeightRef;
                }
              } else {
                height = leftHeight;
              }

              canvas1.width = canvas.width;
              canvas1.height = height;

              // console.log(index, 'height:', height, 'pos', position);

              var ctx = canvas1.getContext('2d');
              ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);

              var pageHeight = Math.round(a4Width / canvas.width * height);
              // pdf.setPageSize(null, pageHeight)
              if (position != 0) {
                pdf.addPage();
              }
              pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 20, a4Width, a4Width / canvas1.width *
                height);
              leftHeight -= height;
              position += height;
              // $('.pdfProgress').text(index + 1);
              // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
              if (leftHeight > 0) {
                //添加全屏水印
                // const base64 = ''
                // for(let i=0;i<6;i++){
                //   for(let j=0;j<5;j++){
                //     const  left = (j*120)+20;
                //     pdf.addImage(base64,'JPEG', left, i*150, 20, 30);
                //   }
                // }
                setTimeout(createImpl, 500, canvas);
              } else {
                // _this.iframeSrc = pdf.output('dataurlstring');
                // debugger;
                this.pdfSave = pdf.save(pdfFileName + '.pdf');
              }
            }
          }

          //当内容未超过pdf一页显示的范围，无需分页
          if (leftHeight < a4HeightRef) {
            pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight);
            this.dialogVisible = true;
            // this.iframeSrc = pdf.output('dataurlstring');
            // debugger;
            this.pdfSave = pdf.save(pdfFileName + '.pdf')
          } else {
            try {
              pdf.deletePage(0);
              // $('.pdfTip').show();
              // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
              setTimeout(createImpl, 500, canvas);

            } catch (err) {
              console.log(err);
            }
          }
        }).then(() => {
          this.printShow = false
          this.pdfNum = parseInt(this.pdfNum)
          this.pdfNum += 1
        }).then(() => {
          this.print()
        })

      },
    }
  }
</script>

<style scoped>

</style>
